<template>
    <div>
        <!-- 面包屑导航 -->
        <el-breadcrumb separator="/">
            <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>商品管理</el-breadcrumb-item>
            <el-breadcrumb-item>分类参数</el-breadcrumb-item>
        </el-breadcrumb>

        <!-- 卡片视图区域 -->
        <el-card>
            <!-- 卡片头部 -->
            <div slot="header">
                <el-alert title="注意：只允许为第三级分类设置相关参数！" type="info" show-icon :closable="false">
                </el-alert>
                <br>
                <span>选择商品分类：</span>
                <el-cascader v-model="goodsCateIdSelected" :options="goodsCateList" :props="goodsCateProps"
                    @change="goodsCateChange" clearable filterable></el-cascader>
            </div>

            <!-- 卡片主体 -->
            <div>
                <el-tabs v-model="activeName">
                    <!-- 动态参数 -->
                    <el-tab-pane label="动态参数" name="many">
                        <!-- 添加参数按钮 -->
                        <el-button type="primary" :disabled="isBtnDisabled" @click="addParams">
                            添加参数
                        </el-button>
                        <!-- 添加参数表格区域 -->
                        <el-table :data="dynamicParameteList" class="addCateTable" border>
                            <el-table-column type="expand">
                                <template slot-scope="scope">
                                    <el-tag v-for="(attr, index) in scope.row.attr_vals" :key="index" closable
                                        @close="dynamicParamsClose(index,scope.row)">
                                        {{ attr }}
                                    </el-tag>
                                    <el-input class="input-new-tag" v-if="scope.row.inputVisible"
                                        v-model="scope.row.inputValue" ref="saveTagInput" size="small"
                                        @keyup.enter.native="handleInputConfirm(scope.row)"
                                        @blur="handleInputConfirm(scope.row)">
                                    </el-input>
                                    <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">
                                        + New Tag
                                    </el-button>
                                </template>
                            </el-table-column>
                            <el-table-column type="index" label="编号" align="center" width="100"></el-table-column>
                            <el-table-column label="参数名称" prop="attr_name"></el-table-column>
                            <el-table-column label="操作" align="center" width="200">
                                <template slot-scope="scope">
                                    <el-button size="mini" type="primary" @click="editParams(scope.row.attr_id)">
                                        编辑
                                    </el-button>
                                    <el-button slot="reference" size="mini" type="danger"
                                        @click="deleteParams(scope.row.attr_id, scope.row.attr_name)">
                                        删除
                                    </el-button>
                                </template>
                            </el-table-column>
                        </el-table>
                    </el-tab-pane>
                    <!-- 静态属性 -->
                    <el-tab-pane label="静态属性" name="only">
                        <!-- 添加属性按钮 -->
                        <el-button type="primary" :disabled="isBtnDisabled" @click="addParams">
                            添加属性
                        </el-button>
                        <!-- 添加属性表格区域 -->
                        <el-table :data="statusPropertiesList" class="addCateTable" border>
                            <el-table-column type="expand">
                                <template slot-scope="scope">
                                    <el-tag v-for="(attr, index) in scope.row.attr_vals" :key="index" closable
                                        @close="dynamicParamsClose(index,scope.row)">
                                        {{ attr }}
                                    </el-tag>
                                    <el-input class="input-new-tag" v-if="scope.row.inputVisible"
                                        v-model="scope.row.inputValue" ref="saveTagInput" size="small"
                                        @keyup.enter.native="handleInputConfirm(scope.row)"
                                        @blur="handleInputConfirm(scope.row)">
                                    </el-input>
                                    <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">
                                        + New Tag
                                    </el-button>
                                </template>
                            </el-table-column>
                            <el-table-column type="index" label="编号" align="center" width="100"></el-table-column>
                            <el-table-column label="属性名称" prop="attr_name"></el-table-column>
                            <el-table-column label="操作" align="center" width="200">
                                <template slot-scope="scope">
                                    <el-button size="mini" type="primary" @click="editParams(scope.row.attr_id)">
                                        编辑
                                    </el-button>
                                    <el-button slot="reference" size="mini" type="danger"
                                        @click="deleteParams(scope.row.attr_id, scope.row.attr_name)">
                                        删除
                                    </el-button>
                                </template>
                            </el-table-column>
                        </el-table>
                    </el-tab-pane>
                </el-tabs>
            </div>
        </el-card>

        <!-- 添加参数对话框 -->
        <el-dialog :title="'添加' + dialogTitle" :visible.sync="addParamsDialogVisible" width="30%"
            :close-on-click-modal="false" @close="addParamsDialogClose">
            <el-form :model="addParamsFormData" :rules="addOrEditParamsFormRules" ref="addParamsFormRef"
                label-width="100px" status-icon>
                <el-form-item :label="dialogTitle" prop="attr_name">
                    <el-input v-model="addParamsFormData.attr_name"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer">
                <el-button @click="addParamsDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="addParamsSubmit()">确 定</el-button>
            </span>
        </el-dialog>

        <!-- 编辑参数对话框 -->
        <el-dialog :title="'编辑' + dialogTitle" :visible.sync="editParamsDialogVisible" width="30%"
            :close-on-click-modal="false" @close="editParamsDialogClose">
            <el-form :model="editParamsFormData" :rules="addOrEditParamsFormRules" ref="editParamsFormRef"
                label-width="100px" status-icon>
                <el-form-item :label="dialogTitle" prop="attr_name">
                    <el-input v-model="editParamsFormData.attr_name"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer">
                <el-button @click="editParamsDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="editParamsSubmit()">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
export default {
    data() {
        return {
            // tab栏被激活的tab
            activeName: 'many',
            // 商品分类列表
            goodsCateList: [],
            // 商品分类的配置对象
            goodsCateProps: {
                expandTrigger: 'hover',
                label: 'cat_name',
                value: 'cat_id',
                children: 'children'
            },
            // 商品分类被选中的id
            goodsCateIdSelected: [],
            // 动态参数列表
            dynamicParameteList: [],
            // 静态属性列表
            statusPropertiesList: [],
            // 对话框的显示与隐藏
            addParamsDialogVisible: false,
            editParamsDialogVisible: false,
            // 表单数据绑定对象
            addParamsFormData: {
                attr_name: ''
            },
            editParamsFormData: {
                attr_name: ''
            },
            // 表单验证规则对象
            addOrEditParamsFormRules: {
                attr_name: [
                    { required: true, message: '请输入名称', trigger: 'blur' },
                    { pattern: /^[^\s]*$/, message: '禁止输入空格', trigger: 'blur' }
                ]
            },
        };
    },
    created() {
        // 获取商品分类数据
        this.getGoodsCateData();
    },
    methods: {
        // 获取商品分类数据
        async getGoodsCateData() {
            const { data: res } = await this.$http.get('categories');
            if (res.meta.status !== 200) return this.$message.error('获取商品分类数据失败');
            this.goodsCateList = res.data;
        },
        // 商品分类选项改变时触发
        goodsCateChange() {
            if (this.goodsCateIdSelected.length !== 0 && this.goodsCateIdSelected.length !== 3) {
                this.goodsCateIdSelected = [];
                this.dynamicParameteList = [];
                this.statusPropertiesList = [];
                this.$message.info('注意：只允许为第三级分类设置相关参数！');
            } else if (this.goodsCateIdSelected.length !== 3) {
                this.goodsCateIdSelected = [];
                this.dynamicParameteList = [];
                this.statusPropertiesList = [];
            } else {
                // 获取动态参数数据
                this.getDynamicParameter();
                // 获取静态属性数据
                this.getStatusProperties();
            }
        },
        // 获取动态参数数据
        async getDynamicParameter() {
            const { data: res } = await this.$http.get(`categories/${this.cateId}/attributes`,
                {
                    params: { sel: 'many' }
                });
            if (res.meta.status !== 200) return this.$message.error('动态参数列表获取失败');

            res.data.forEach(item => {
                // 将动态参数下的字符串数据转换为数组
                item.attr_vals = item.attr_vals ? item.attr_vals.split(' ') : [];
                // 控制输入框的显示与隐藏
                item.inputVisible = false;
                // 输入框内双向绑定的值
                item.inputValue = '';
            })
            this.dynamicParameteList = res.data;
        },
        // 获取静态属性数据
        async getStatusProperties() {
            const { data: res } = await this.$http.get(`categories/${this.cateId}/attributes`, { params: { sel: 'only' } });
            if (res.meta.status !== 200) return this.$message.error('静态属性列表获取失败');
            res.data.forEach(item => {
                // 将动态参数下的字符串数据转换为数组
                item.attr_vals = item.attr_vals ? item.attr_vals.split(' ') : [];
                // 控制输入框的显示与隐藏
                item.inputVisible = false;
                // 输入框内双向绑定的值
                item.inputValue = '';
            })
            this.statusPropertiesList = res.data;
        },
        // 动态参数下的值关闭事件
        dynamicParamsClose(i, row) {
            row.attr_vals.splice(i, 1);
            this.saveAttrVals(row);
        },
        // 对话框的关闭事件
        addParamsDialogClose() {
            this.$refs.addParamsFormRef.resetFields();
        },
        editParamsDialogClose() {
            this.$refs.editParamsFormRef.resetFields();
        },
        // 添加参数
        addParams() {
            this.addParamsDialogVisible = true;
        },
        // 编辑参数
        editParams(attr_id) {
            this.editParamsDialogVisible = true;
            // 数据回写
            this.getEditParamsData(attr_id);
        },
        // 数据回写
        async getEditParamsData(attr_id) {
            const { data: res } = await this.$http.get(`categories/${this.cateId}/attributes/${attr_id}`, {
                params: { attr_sel: this.attr_sel }
            })
            if (res.meta.status !== 200) return this.$message.error('参数获取失败');
            this.editParamsFormData = res.data;
        },
        // 确定 添加参数
        addParamsSubmit() {
            this.$refs.addParamsFormRef.validate(async valid => {
                if (!valid) return;
                const { data: res } = await this.$http.post(`categories/${this.cateId}/attributes`, {
                    attr_name: this.addParamsFormData.attr_name,
                    attr_sel: this.activeName
                });
                if (res.meta.status !== 201) return this.$message.error(`添加${this.dialogTitle}失败`);
                this.$message.success(`添加${this.dialogTitle}成功`);
                this.getDynamicParameter();
                this.getStatusProperties();
                this.addParamsDialogVisible = false;
            })
        },
        // 确定 编辑参数
        editParamsSubmit() {
            this.$refs.editParamsFormRef.validate(async valid => {
                if (!valid) return;
                const { data: res } = await this.$http.put(`categories/${this.cateId}/attributes/${this.editParamsFormData.attr_id}`, {
                    attr_name: this.editParamsFormData.attr_name,
                    attr_sel: this.activeName
                });
                if (res.meta.status !== 200) return this.$message.error(`编辑${this.dialogTitle}失败`);
                this.$message.success(`编辑${this.dialogTitle}成功`);
                this.getDynamicParameter();
                this.getStatusProperties();
                this.editParamsDialogVisible = false;
            })
        },
        // 删除参数 按钮
        deleteParams(attr_id, attr_name) {
            this.$confirm(`此操作将删除 ${attr_name} 参数, 是否继续?`, '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(async () => {
                const { data: res } = await this.$http.delete(`categories/${this.cateId}/attributes/${attr_id}`);
                if (res.meta.status !== 200) return this.$message.error('删除失败');
                this.$message({
                    type: 'success',
                    message: '删除成功!'
                });
                this.getDynamicParameter();
                this.getStatusProperties();
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消删除'
                });
            });
        },
        // 回车或鼠标失去焦点触发输入框确认
        async handleInputConfirm(row) {
            if (row.inputValue.trim().length === 0) {
                row.inputValue = '';
                row.inputVisible = false;
                return
            }
            row.attr_vals.push(row.inputValue.trim())
            row.inputValue = '';
            row.inputVisible = false;
            this.saveAttrVals(row);
        },
        // 保存参数的值
        async saveAttrVals(row) {
            const { data: res } = await this.$http.put(`categories/${this.cateId}/attributes/${row.attr_id}`,
                {
                    attr_name: row.attr_name,
                    attr_sel: this.activeName,
                    attr_vals: row.attr_vals.join(' ')
                });
            if (res.meta.status !== 200) return this.$message.error('修改参数失败');
            this.$message.success('修改参数成功');
        },
        // 显示输入框
        showInput(row) {
            row.inputVisible = true;
            // 自动获取焦点
            // $nextTick 方法的作用，当页面上的元素被重新渲染之后，才会执行回调函数中的代码
            this.$nextTick(_ => {
                this.$refs.saveTagInput.$refs.input.focus();
            });
        },
    },
    computed: {
        // 按钮禁用
        isBtnDisabled() {
            if (this.goodsCateIdSelected.length !== 3) {
                return true;
            }
            return false;
        },
        // 动态渲染对话框标题及文本
        dialogTitle() {
            if (this.activeName === 'many') {
                return '动态参数';
            } else {
                return '静态属性';
            }
        },
        // 获取三级分类id
        cateId() {
            if (this.goodsCateIdSelected.length !== 3) {
                return;
            }
            return this.goodsCateIdSelected[2];
        },
    }
}
</script>

<style lang="less" scoped>
.addCateTable {
    margin-top: 14px;
}

.el-tag {
    margin: 10px;
}

.input-new-tag {
    width: 120px;
}
</style>
